package com.xunshibao.tutor.user.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xunshibao.core.BaseDRO;
import com.xunshibao.core.security.SecurityUtils;
import com.xunshibao.core.web.SessionUser;
import com.xunshibao.tutor.po.User;
import com.xunshibao.tutor.user.service.UserLoginServiceImpl;

@Controller(value="loginController")
@RequestMapping(value="/user/*")
public class UserLoginController {
    @Autowired
    private UserLoginServiceImpl loginService;
    
    @RequestMapping(value="login", method=RequestMethod.POST)
    public @ResponseBody Map<String, Object> login(@RequestParam(value="uname")String username, @RequestParam(value="pwd")String password, HttpServletRequest request){
        Map<String, Object> json = new HashMap<String, Object>();
        String ip = request.getRemoteAddr();
        BaseDRO dro = loginService.login(username, password, ip);
        if(dro.getStatus() == 0) {
        	User user = (User)dro.getResult();
        	SessionUser su = new SessionUser(user.getId());
        	SecurityUtils.saveUserToSession(request.getSession(), su);
        	  json.put("username", user.getUname());
              json.put("uid", user.getId());
        }
        json.put("status", dro.getStatus());
      
        return json;
    }
    
    @RequestMapping(value="register", method=RequestMethod.POST)
    public @ResponseBody Map<String, Object> register(@RequestParam(value="uname")String username, @RequestParam(value="pwd")String password, HttpServletRequest request){
        Map<String, Object> json = new HashMap<String, Object>();
        String ip = request.getRemoteAddr();
        int result = loginService.register(username, password, ip);
        json.put("status", result);
        return json;
    }
    
    
    @RequestMapping(value="login", method=RequestMethod.GET)
    public String login(/*@RequestParam(value="url", defaultValue="#{servletPath}/index")String redirectUrl*/) {
        return "user/login";
    }
    
    @RequestMapping(value="register", method=RequestMethod.GET)
    public String register() {
        return "user/register";
    }
}
